﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Entities = GMAC.ReportingSystem.Business.Entities;
using System.Data;
using Components = GMAC.ReportingSystem.Business.Components;
using FrameworkManapro.Utilities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class AccountRepresentatives : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
        }

        #endregion

        #region Button Events

        
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
           btnSave.Visible = false;
            btnNew.Visible = true;
            var frc = new  Components.AccountRepresentativeComponent();
            try
            {
                var AccountRepresentative = ReadAccountRepresentative();
                if (hfAccountRepresentativeID.Value.Trim() != string.Empty)
                {
                    AccountRepresentative.ID = int.Parse(hfAccountRepresentativeID.Value);
                    var oldAccountRepresentative = frc.GetDetails(AccountRepresentative.ID);
                    frc.Edit(AccountRepresentative);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.AccountRepresentative>
                    {
                        EntityKey = AccountRepresentative.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldAccountRepresentative,
                        NewObject = AccountRepresentative,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.AccountRepresentative>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The AccountRepresentative was successfully saved.", null);
                    popupExtenderMessage.Show();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save AccountRepresentative", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The AccountRepresentative couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
           if (grvAccountRepresentatives != null)
            {
                if (grvAccountRepresentatives.SelectedDataKey != null)
                {
                    try
                    {
                        var AccountRepresentativeId = (int)this.grvAccountRepresentatives.SelectedDataKey.Value;
                        var frc = new Components.AccountRepresentativeComponent();
                        var AccountRepresentative = frc.GetDetails(AccountRepresentativeId);
                        hfAccountRepresentativeID.Value = AccountRepresentativeId.ToString();
                        txtFirstName.Text = AccountRepresentative.FistName;
                        txtLastName.Text = AccountRepresentative.LastName;
                        txtEmail.Text = AccountRepresentative.Email;
                        txtPhone.Text = AccountRepresentative.Phone;
                        txtClientIdentificationNumber.Text = AccountRepresentative.IdentificationNumber;
                        btnSave.Visible = true;
                        btnNew.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify AccountRepresentative", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the AccountRepresentative.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A Account Representative must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }
        
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
              try
            {
                var frc = new Components.AccountRepresentativeComponent();
                if (grvAccountRepresentatives.SelectedDataKey != null)
                {
                    var AccountRepresentativeId = (int)this.grvAccountRepresentatives.SelectedDataKey.Value;
                    var AccountRepresentative = new Entities.AccountRepresentative { ID = AccountRepresentativeId };
                    var oldAccountRepresentative = frc.GetDetails(AccountRepresentative.ID);
                    frc.Delete(AccountRepresentative);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.AccountRepresentative>
                    {
                        EntityKey = AccountRepresentative.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldAccountRepresentative,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.AccountRepresentative>(audit);
                    auditDAC.InsertAudit();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The AccountRepresentative was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete AccountRepresentative", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The AccountRepresentative couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            }
            ClearFields();
            
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvAccountRepresentatives.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A AccountRepresentative must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.AccountRepresentativeComponent();
                var AccountRepresentative = ReadAccountRepresentative();
                AccountRepresentative.ID = frc.Create(AccountRepresentative);
                var audit = new FrameworkManapro.Audit.Audit<Entities.AccountRepresentative>
                {
                    EntityKey = AccountRepresentative.ID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = AccountRepresentative,
                    UserId = ((Entities.User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.AccountRepresentative>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Account Representative was successfully saved.", null);
                popupExtenderMessage.Show();
                this.PagingControl.TotalRecords = Search();
                Search();

                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Account Representative", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Account Representative could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        #endregion

        #region Other Events

        protected void grvAccountRepresentatives_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvAccountRepresentatives, "Select$" + e.Row.RowIndex);
            }
        }

        #endregion

        #region Private Methods

        private void ClearFields()
        {
            txtFirstName.Text = string.Empty;
            txtLastName.Text= string.Empty;
            txtClientIdentificationNumber.Text= string.Empty;
            txtEmail.Text= string.Empty;
            txtPhone.Text= string.Empty;
            hfAccountRepresentativeID.Value = string.Empty;

        }
        private void Initialize()
        {
            try
            {
                btnSave.Visible = false;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected Account Representative", null);
                this.PagingControl.TotalRecords = Search();
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }

        }

        private void ValidateSecurity()
        {
            var beEntities = ((Entities.User)Session["User"]).Role.Security.GetEntitySecurity("AccountRepresentatives");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvAccountRepresentatives.Visible = false;
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }
        private int Search()
        {
            try
            {
                var bc = new  Components.AccountRepresentativeComponent();
                string FirstName = txtFirstNameSearch.Text;
                string LastName = txtLastNameSearch.Text;
                string IdentificationNumber = txtClientIdentificationNumberSearch.Text;
                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;

                Entities.AccountRepresentativeCollection AccountRepresentativecollection = bc.Search(FirstName, LastName, IdentificationNumber, paging);

                grvAccountRepresentatives.DataSource = AccountRepresentativecollection;
                grvAccountRepresentatives.DataBind();
                return AccountRepresentativecollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Account Representative", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return  0;

            }
        }
        private Entities.AccountRepresentative ReadAccountRepresentative()
        {
            var AccountRepresentative = new  Entities.AccountRepresentative
            {
                 FistName = txtFirstName.Text,
                 LastName = txtLastName.Text,
                 IdentificationNumber = txtClientIdentificationNumber.Text,
                 Email = txtEmail.Text,
                 Phone = txtPhone.Text,
           };
            if (AccountRepresentative.Phone =="____-_______")
            {
                AccountRepresentative.Phone = "";
            }
            if (!string.IsNullOrEmpty(hfAccountRepresentativeID.Value))
            {
                AccountRepresentative.ID = int.Parse(hfAccountRepresentativeID.Value);
            }
               
            return AccountRepresentative;
        }
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
            Search();
        }
        #endregion

    }
}
